package cn.fenglaicaimi.controller;

import cn.fenglaicaimi.base.domain.MessageRequestVo;
import cn.fenglaicaimi.base.domain.MessageResponseVo;
import cn.fenglaicaimi.util.SecurityUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Date;
import java.util.TreeSet;

@Controller
public class WechatControllor {
	@Value("${wechat.token}")
	private String token;

	/**
	 * signature	微信加密签名，signature结合了开发者填写的token参数和请求中的timestamp参数、nonce参数。
		timestamp	时间戳
		nonce	随机数
		echostr	随机字符串
	 * @return
	 */
	@RequestMapping(value = "wechat",method = RequestMethod.GET)
	@ResponseBody
	public String wechat( String signature,String timestamp,String nonce,String echostr){
		//1）将token、timestamp、nonce三个参数进行字典序排序
		TreeSet<String> set = new TreeSet<String>();
		set.add(token);
		set.add(timestamp);
		set.add(nonce);		
		//2）将三个参数字符串拼接成一个字符串进行sha1加密
		StringBuilder sb = new StringBuilder();
		for (String str : set) {
			sb.append(str);
		}
		String ret = SecurityUtil.SHA1(sb.toString());
		//3）开发者获得加密后的字符串可与signature对比，标识该请求来源于微信
		//ret和signature进行匹配，相等返回echostr接入成功，否则接入失败
		if (ret.equals(signature)) {
			return echostr;
		}
		return "success";
		//return echostr;
	}
	
	
	@RequestMapping(value = "wechat",method = RequestMethod.POST)
	@ResponseBody
	public Object wechat(@RequestBody MessageRequestVo requestVo){
		if ("text".equals(requestVo.getMsgType())) {
			//文本消息
			return sendMsg(requestVo,"好的");
		}else if ("image".equals(requestVo.getMsgType())) {
			//图片消息的逻辑业务
			return sendMsg(requestVo,"图片消息的逻辑业务");
		}else if("event".equals(requestVo.getMsgType())){
			if ("subscribe".equals(requestVo.getEvent())) {
				return sendMsg(requestVo,"欢迎订阅");
			}else if("unsubscribe".equals(requestVo.getEvent())){
				//做一个取关业务逻辑的操作
				return "unsubscribe";
			}
		}
		return "success";
	}


	private MessageResponseVo sendMsg(MessageRequestVo requestVo, String content) {
		MessageResponseVo responseVo = new MessageResponseVo();
		responseVo.setContent(content);
		responseVo.setCreateTime(new Date().getTime());
		responseVo.setFromUserName(requestVo.getToUserName());
		responseVo.setMsgType("text");
		responseVo.setToUserName(requestVo.getFromUserName());
		return responseVo;
	}
}
